/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var xmlProductDoc = null;
var updatedProduct = new Array();


function Product(id, name, price, quantity, category, isShowed, isDeleted, imageUrl) {
    var product = new Object();
    product.id = id;
    product.name = name;
    product.price = price;
    product.quantity = quantity;
    product.category = category;
    product.isShowed = isShowed;
    product.isDeleted = isDeleted;
    product.imageUrl = imageUrl;
    return product;
}

function loadProductXML() {
    if (xmlProductDoc == null) {
        var xmlHttp = getXMLObject();

        var url = "../product/searchProductXMLCallback.html";


        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4) {
                if(xmlHttp.status == 200) {
                    xmlProductDoc = xmlHttp.responseXML;
                //updateProduct(id);
                }
            }
        }

        xmlHttp.open("POST", url, false);

        xmlHttp.send();
    //    } else {
    //        updateProduct(id);
    }
    
}

function updateProduct(productTableId) {
    if (xmlProductDoc == null) {
        loadProductXML();
    }
    var form = document.forms["updateProductForm_"+productTableId];
    var id = form.id.value;
    var name = form.name.value;
    var price = form.price.value;
    var quantity = form.quantity.value;
    var category = form.category.value;
    var showed = form.showed.checked;
    var deleted = form.deleted.checked;
    var imageUpdate = "";
    if (!form.images.value == "") {
        imageUpdate = "../productImage/"+form.images.value;
    }
   
    var product = Product(id, name,price, quantity, category, showed, deleted, imageUpdate);

    var path = "/products/product[@id = '"+ product.id +"']";

    if (xmlProductDoc.evaluate) {
        var iterator = xmlProductDoc.evaluate(path, xmlProductDoc, nsResolverProduct, XPathResult.FIRST_ORDERED_NODE_TYPE ,null);

        try {
            //Update DOM
            //iterator.singleNodeValue.getElementsByTagName("username")[0].textContent = user.username;
            iterator.singleNodeValue.getElementsByTagName("name")[0].textContent = product.name;
            iterator.singleNodeValue.getElementsByTagName("price")[0].textContent = product.price;
            iterator.singleNodeValue.getElementsByTagName("quantity")[0].textContent = product.quantity;
            iterator.singleNodeValue.getElementsByTagName("category")[0].textContent = product.category;
            iterator.singleNodeValue.getElementsByTagName("isshowed")[0].textContent = product.isShowed;
            iterator.singleNodeValue.getElementsByTagName("isdeleted")[0].textContent = product.isDeleted;
            if (product.imageUrl != "") {
                iterator.singleNodeValue.getElementsByTagName("url")[0].textContent = product.imageUrl;
            }
            
        }catch (e) {
            alert('Error : Document tree when updating.' + e);
        }
        updateProductRow(product, productTableId);
        alert("Update successful.");
        //Add id to updatedUsers
        addIdToUpdatedProductList(product.id);

        //Clear image
//        document.getElementById("resultImageUpdate").hidden = true;
//        document.getElementById("resultImage").hidden = true;
        document.getElementById('close').click();

    } else {
        alert("Update fail. Please try again.")
    }
    return false;

}

function deleteProduct(id, productTableId) {
    var confirmDelete = confirm("Are you sure?");
    if (confirmDelete == true) {
        var xmlHttp = getXMLObject();
        var url = "../adminproduct/delete.html?productId="+id;

        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                if (xmlHttp.responseText == "OK") {
                    var table = document.getElementById("tblProduct");
                    var deleteButton = table.rows[productTableId].cells[8].childNodes[0].innerHTML;
                    var checkIsDeleted = table.rows[productTableId].cells[6].childNodes[0];
                    if (deleteButton == "Delete") {
                        checkIsDeleted.checked = true;
                        table.rows[productTableId].cells[8].childNodes[0].innerHTML = "UnDelete"
                    } else if (deleteButton == "UnDelete") {
                        checkIsDeleted.checked = false;
                        table.rows[productTableId].cells[8].childNodes[0].innerHTML = "Delete"
                    }
                }
                else {
                    setTimeout(function(){
                        document.location.href = "../error.html"
                    },500);
                }
            }
        }
        xmlHttp.open("POST", url, true);
        xmlHttp.send();
    } 
}

function nsResolverProduct(prefix) {
    var ns = {
        'p' : 'http://xml.netbeans.org/schema/',
        'i': 'http://xml.netbeans.org/schema/image'
    };
    return ns[prefix] || null;
}

function updateProductRow(product, id) {
    var table = document.getElementById("tblProduct");
    table.rows[id].cells["name"].innerHTML = product.name;
    table.rows[id].cells["price"].innerHTML = product.price;
    table.rows[id].cells["quantity"].innerHTML = product.quantity;
    table.rows[id].cells["image"].childNodes[0].src = product.imageUrl;
    if (product.isShowed.toString() == "true") {
        table.rows[id].cells["isShowed"].innerHTML = "<input id='isShowed' disabled='disabled' type='checkbox' name='showed' value="+product.isShowed+" checked/>";
    } else {
        table.rows[id].cells["isShowed"].innerHTML = "<input id='isShowed' disabled='disabled' type='checkbox' name='showed' value="+product.isShowed+"/>";
    }

    if (product.isDeleted.toString() == "true") {
        table.rows[id].cells["isDeleted"].innerHTML = "<input id='isDeleted' disabled='disabled' type='checkbox' name='showed' value="+product.isDeleted+" checked/>";
    } else {
        table.rows[id].cells["isDeleted"].innerHTML = "<input id='isDeleted' disabled='disabled' type='checkbox' name='showed' value="+product.isDeleted+"/>";
    }
    
}

function sendProductDomToServer(inputStream, url, callbackfunction, updatedId) {
    var xmlHttp = getXMLObject();
    var stringUpdatedId = "";

    for (var i = 0; i < updatedId.length; i++) {
        stringUpdatedId += (updatedId[i] + ",");
    }
    var resultStream = '&resultStream='+ (new XMLSerializer()).serializeToString(inputStream) + "&updatedProduct=" + stringUpdatedId;


    xmlHttp.open("POST", url, false);

    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


    xmlHttp.onreadystatechange = function() {
        callbackfunction(xmlHttp);
    }

    xmlHttp.send(resultStream);

}

function callBackFunctionForSendXMLToServer(xmlHttp) {
    if (xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            alert("OK");
        }
    }
}

function loadCategory(id) {
    var tocategories = document.getElementById(id);
    var fromcategories = document.getElementById("addCategory").childNodes;
    var element;
    for (var i = 0; i < fromcategories.length; i++) {
        if (fromcategories[i].value != null) {
            if (tocategories.childNodes[0].value != fromcategories[i].value) {
                element = fromcategories[i];
                tocategories.appendChild(element);
            }
        }       
    }    
}

function addIdToUpdatedProductList(id) {
    var isfound = true;

    for (var i = 0; isfound && i < updatedProduct.length; ++i) {
        if (updatedProduct[i] == id) {
            isfound = false;
        }
    }
    if (isfound) {
        updatedProduct.push(id);
    }
}

var fieldToSortProduct = "name";
var sortOrderProduct = "ascending";
function sortProduct(field, id, dataType) {
    //Load doc

    if (fieldToSortProduct == field) {
        sortOrderProduct = (sortOrderProduct == "ascending") ? "descending" : "ascending";
    } else {
        fieldToSortProduct = field;
        sortOrderProduct = "ascending";
    }

    

    var xml = loadXML("../product/searchProductXMLCallback.html");
    var xsl = loadXML("../adminproduct/getXSLT.html");


    if (document.implementation && document.implementation.createDocument) {
        xsltProcessor=new XSLTProcessor();
        xsltProcessor.importStylesheet(xsl);
        //Get sort parameter
        xsltProcessor.setParameter(null, "fieldToSort", field);
        xsltProcessor.setParameter(null, "sortCondition", sortOrderProduct);
        xsltProcessor.setParameter(null, "dataType", dataType);
        resultDocument = xsltProcessor.transformToFragment(xml,document);
        document.getElementById("productConcac").innerHTML = "";
        document.getElementById("productConcac").appendChild(resultDocument);

        //        var className = document.getElementById(id).className;

        document.getElementById(id).className = (sortOrderProduct == "ascending") ? "sorting_desc": "sorting_asc";
    }
}

function clearAddProduct() {
    var divImage = document.getElementById("resultImage");
    divImage.src = "";
    divImage.hidden = true;
}





